package com.kapukapu.authorization.service;

import com.kapukapu.authorization.service.feign.IUserService;
import com.kapukapu.authorization.util.UserInfoHodler;
import com.kapukapu.common.api.user.dto.AuthUserDTO;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.ObjectUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: sivan
 * @date: 2020/03/03
 * @email: zifanuu@gmail.com
 */
public class UserDetailsServiceImpl implements UserDetailsService {
	private final IUserService userService;

	public UserDetailsServiceImpl(IUserService userService) {
		this.userService = userService;
	}

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		AuthUserDTO user = userService.getLoginInfoByUsername(username);

		if (ObjectUtils.isEmpty(user.getUsername())) {
			throw new UsernameNotFoundException(String.format("%s not found.", username));
		}

		List<SimpleGrantedAuthority> authorities;
		if (ObjectUtils.isEmpty(user.getRoles())) {
			authorities = Collections.EMPTY_LIST;
		} else {
			authorities = user.getRoles().stream().map(SimpleGrantedAuthority::new)
				.collect(Collectors.toList());
		}

		UserInfoHodler.setUserInfo(user);
		return new User(user.getUsername(), user.getPassword(), authorities);
	}
}
